const express = require('express');
const router = express.Router();
const { User } = require('../../models');
const { Op } = require('sequelize');
const { BadRequest, Unauthorized, NotFound } = require('http-errors');
const { success, failure } = require('../../utils/responses');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
// const crypto = require('crypto')

/**
 * 管理员登录
 *
 * POST /admin/auth/sign_in
 * */

router.post('/sign_in', async function (req, res) {
  try {
    const { login, password } = req.body;
    // console.log(req.body,'999999', crypto.randomBytes(32).toString('hex'))
    if (!login) {
      throw new BadRequest('邮箱用户名必须填写');
    }
    if (!password) {
      throw new BadRequest('密码必须填写');
    }
    const condition = {
      where: {
        [Op.or]: [{ email: login }, { username: login }],
      },
    };

    const user = await User.findOne(condition);
    if (!user) {
      throw new NotFound('用户不存在');
    }
    const isPasswordValid = bcrypt.compareSync(password, user.password);
    if (!isPasswordValid) {
      throw new Unauthorized('密码错误');
    }
    if (user.role !== 100) {
      throw new Unauthorized('没有登录权限');
    }
    const token = jwt.sign(
      {
        userId: user.id,
      },
      process.env.SECRET,
      { expiresIn: '24h' }
    );
    success(res, '登录成功', { token });
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
